package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.*;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;

    @Reference
    private ReportService reportService;

    @RequestMapping("/add")
    public Result add(@RequestBody Member member){
        try{
            memberService.add(member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception {
        return memberService.findPage(queryPageBean);
    }

/*    @PreAuthorize("hasAnyAuthority('MEMBER_DELETE')")*/
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try{
            memberService.delete(id);
        }catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        }catch (Exception e){
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member){
        try{
            memberService.edit(member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
    }

    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<Member>list=memberService.findAll();
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    /*@RequestMapping("/findAll")
    public Result findByTelephone(String telephone){
        try{
            memberService.findByTelephone(telephone);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }
        return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS);
    }*/

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Member member=memberService.findById(id);
            return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    @RequestMapping("/exportMemberReport")
    public Result exportMemberReport(Integer[] ids,HttpServletRequest request,HttpServletResponse response){
        try{
            //获取Excel模板路径
            String filePath=request.getSession().getServletContext().getRealPath("template")+File.separator+"MemberReport.xlsx";

            //读取模板文件创建excel表格对象
            XSSFWorkbook excel=new XSSFWorkbook(new FileInputStream(new File(filePath)));

            //读取第一个工作表
            XSSFSheet sheet=excel.getSheetAt(0);

            List<Map<String,Object>>result=memberService.getMemberReport(ids);

            for (int i = 0; i < result.size(); i++) {
                Map<String,Object> map=result.get(i);
                String memberName= (String) map.get("memberName");
                String memberSex= (String) map.get("memberSex");
                String memberPhoneNumber= (String) map.get("memberPhoneNumber");
                List<String> Address= (List<String>) map.get("address");
                String setmealName= (String) map.get("setmealName");
                List<String> groupNames= (List<String>) map.get("groupNames");
                List<String> itemName= (List<String>) map.get("itemName");

                //将结果写入excel里
                XSSFRow row=sheet.getRow(i+1);
                if (row == null&&row.getCell(i) == null) {
                    row.createCell(i).setCellValue(new HSSFRichTextString(String.valueOf(map.get(i))));
                 }
                row.getCell(0).setCellValue(memberName);
                row.getCell(1).setCellValue(memberSex);
                row.getCell(2).setCellValue(memberPhoneNumber);
                if (Address!=null){
                    row.getCell(3).setCellValue(Address.toString());
                }
                row.getCell(4).setCellValue(setmealName);
                if (groupNames!=null){
                    row.getCell(5).setCellValue(groupNames.toString());
                }
               if (itemName!=null){
                   row.getCell(6).setCellValue(itemName.toString());
               }

            }
            //通过输出流进行下载
            ServletOutputStream out=response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=MemberReport.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL)  ;
        }
    }

    @RequestMapping("/findManagers")
    public Result findManagers(){
        System.out.println("findMamager is running ...");
        List<Map>list=null;
        try{
            list=memberService.getManagers();
        }catch (Exception e){
            return new Result(false,null);
        }
        return new Result(true,null,list);
    }
}
